package test.mapper;

import JDBC.DBUtil;
import test.vo.Article;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class ArticleMapper {
    public int insertArticle(Article article){
        int num = 0;
        try (Connection con= DBUtil.getConnection()){
            String sql = "INSERT INTO article(title,content) VALUES(?,?)";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1,article.getTitle());
            ps.setString(2,article.getContent());
            num = ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return num;
    }
    public int deleteArticle(int id){
        int num = 0;
        try (Connection con= DBUtil.getConnection()){
            String sql = "DELETE FROM Article WHERE id=?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setInt(1,id);
            num = ps.executeUpdate();
            return num;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    public Article findbyId(int id){
        Article article = new Article();
        try (Connection con= DBUtil.getConnection()){
            String sql = "SELECT title,content FROM Article WHERE id=?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setInt(1,id);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                String title = rs.getString("title");
                String content = rs.getString("content");
                article.setTitle(title);
                article.setContent(content);
                return article;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public List<Article> findAll(){
        List<Article> articlelist = new ArrayList<>();
        try (Connection con= DBUtil.getConnection()){
            String sql = "SELECT title,content FROM Article ";
            Statement sta = con.createStatement();
            ResultSet rs = sta.executeQuery(sql);
            if(rs.next()){
                String title = rs.getString("title");
                String content = rs.getString("content");
                Article article = new Article();
                article.setTitle(title);
                article.setContent(content);
                articlelist.add(article);
                return articlelist;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
